package org.oc.qaq.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.oc.qaq.annotation.Autofill;
import org.oc.qaq.constant.AutoFillConstant;
import org.oc.qaq.enumeration.OperationType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
public class AutofillAspect {
    @Pointcut("execution(* org.oc.qaq.mapper.*.*(..)) && @annotation(org.oc.qaq.annotation.Autofill)")
    public void AutofillPointCut() {
    }

    @Before("AutofillPointCut()")
    public void Autofill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Object[] args = joinPoint.getArgs();
        Object entity = args[0];

        LocalDateTime now = LocalDateTime.now();
        String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();

        Autofill annotation = method.getAnnotation(Autofill.class);
        if (annotation != null) {
            if (annotation.value() == OperationType.INSERT) {
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, String.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, String.class);

                setCreateTime.invoke(entity, now);
                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, currentUser);
                setCreateUser.invoke(entity, currentUser);

            } else if (annotation.value() == OperationType.UPDATE) {
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, String.class);

                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, currentUser);
            }
        }

    }
}
